<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>vue-axios封装请求（十二） | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="Vue,">
  

  <meta name="description" content="一、axios 简介 axios 是一个基于Promise用于浏览器和 nodejs 的 HTTP 客户端，它本身具有以下特征：   从浏览器中创建 XMLHttpRequest 从 node.js 发出 http 请求 支持Promise API 拦截请求和响应 转换请求和响应数据 取消请求 自动转换JSON数据 客户端支持防止CSRF/XSRF  二、axios基础 axios.request">
<meta name="keywords" content="Vue">
<meta property="og:type" content="article">
<meta property="og:title" content="vue-axios封装请求（十二）">
<meta property="og:url" content="http://blog.poetries.top/2018/08/28/vue-axios/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、axios 简介 axios 是一个基于Promise用于浏览器和 nodejs 的 HTTP 客户端，它本身具有以下特征：   从浏览器中创建 XMLHttpRequest 从 node.js 发出 http 请求 支持Promise API 拦截请求和响应 转换请求和响应数据 取消请求 自动转换JSON数据 客户端支持防止CSRF/XSRF  二、axios基础 axios.request">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-08-15T04:25:31.938Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="vue-axios封装请求（十二）">
<meta name="twitter:description" content="一、axios 简介 axios 是一个基于Promise用于浏览器和 nodejs 的 HTTP 客户端，它本身具有以下特征：   从浏览器中创建 XMLHttpRequest 从 node.js 发出 http 请求 支持Promise API 拦截请求和响应 转换请求和响应数据 取消请求 自动转换JSON数据 客户端支持防止CSRF/XSRF  二、axios基础 axios.request">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、axios-简介"><span class="toc-text">一、axios 简介</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、axios基础"><span class="toc-text">二、axios基础</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、执行-GET-请求"><span class="toc-text">三、执行 GET 请求</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四、执行-POST-请求"><span class="toc-text">四、执行 POST 请求</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#五、通过配置方式发送请求"><span class="toc-text">五、通过配置方式发送请求</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#六、执行多个并发请求"><span class="toc-text">六、执行多个并发请求</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#七、全局拦截"><span class="toc-text">七、全局拦截</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#八、请求封装、异常统一处理"><span class="toc-text">八、请求封装、异常统一处理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#8-1-axios-请求封装"><span class="toc-text">8.1 axios 请求封装</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-2-axios请求异常统一处理"><span class="toc-text">8.2 axios请求异常统一处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#8-3-vue-项目中使用该方法"><span class="toc-text">8.3 vue 项目中使用该方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#九、接口封装处理"><span class="toc-text">九、接口封装处理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#9-1-axios的封装"><span class="toc-text">9.1 axios的封装</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-2-环境的切换"><span class="toc-text">9.2 环境的切换</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-3-设置请求超时"><span class="toc-text">9.3 设置请求超时</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-4-请求拦截"><span class="toc-text">9.4 请求拦截</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-5-响应的拦截"><span class="toc-text">9.5 响应的拦截</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-6-封装get方法和post方法"><span class="toc-text">9.6 封装get方法和post方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-7-api的统一管理"><span class="toc-text">9.7 api的统一管理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#9-8-完整封装代码"><span class="toc-text">9.8 完整封装代码</span></a></li></ol></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-vue-axios" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">vue-axios封装请求（十二）</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2018.08.28</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 4.4k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 19分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、axios-简介"><a href="#一、axios-简介" class="headerlink" title="一、axios 简介"></a>一、axios 简介</h2><blockquote>
<p><code>axios</code> 是一个基于<code>Promise</code>用于浏览器和 <code>nodejs</code> 的 <code>HTTP</code> 客户端，它本身具有以下特征：</p>
</blockquote>
<ul>
<li>从浏览器中创建 <code>XMLHttpRequest</code></li>
<li>从 <code>node.js</code> 发出 <code>http</code> 请求</li>
<li>支持<code>Promise API</code></li>
<li>拦截请求和响应</li>
<li>转换请求和响应数据</li>
<li>取消请求</li>
<li>自动转换<code>JSON</code>数据</li>
<li>客户端支持防止<code>CSRF/XSRF</code></li>
</ul>
<h2 id="二、axios基础"><a href="#二、axios基础" class="headerlink" title="二、axios基础"></a>二、axios基础</h2><ul>
<li><code>axios.request（config）</code></li>
<li><code>axios.get（url [，config]）</code></li>
<li><code>axios.delete（url [，config]）</code></li>
<li><code>axios.head（url [，config]）</code></li>
<li><code>axios.options（url [，config]）</code></li>
<li><code>axios.post（url [，data [，config]]</code>）</li>
<li><code>axios.put（url [，data [，config]]）</code></li>
<li><code>axios.patch（url [，data [，config]]）</code></li>
</ul>
<h2 id="三、执行-GET-请求"><a href="#三、执行-GET-请求" class="headerlink" title="三、执行 GET 请求"></a>三、执行 GET 请求</h2><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 向具有指定ID的用户发出请求</span></span><br><span class="line">axios.get(<span class="string">'/user?ID=12345'</span>)</span><br><span class="line">.then(<span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res);</span><br><span class="line">&#125;)</span><br><span class="line">.catch(<span class="function"><span class="keyword">function</span> (<span class="params">error</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(error);</span><br><span class="line">&#125;);</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 也可以通过 params 对象传递参数</span></span><br><span class="line">axios.get(<span class="string">'/user'</span>, &#123;</span><br><span class="line">    params: &#123;</span><br><span class="line">        ID: <span class="number">12345</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line">.then(<span class="function"><span class="keyword">function</span> (<span class="params">response</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(response);</span><br><span class="line">&#125;)</span><br><span class="line">.catch(<span class="function"><span class="keyword">function</span> (<span class="params">error</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(error);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="四、执行-POST-请求"><a href="#四、执行-POST-请求" class="headerlink" title="四、执行 POST 请求"></a>四、执行 POST 请求</h2><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">axios.post(<span class="string">'/user'</span>, &#123;</span><br><span class="line">    userId:<span class="string">"123"</span></span><br><span class="line">&#125;,&#123;</span><br><span class="line">    headers:&#123;</span><br><span class="line">        token:<span class="string">"abc"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line">.then(<span class="function"><span class="keyword">function</span> (<span class="params">res</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res);</span><br><span class="line">&#125;)</span><br><span class="line">.catch(<span class="function"><span class="keyword">function</span> (<span class="params">error</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(error);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="五、通过配置方式发送请求"><a href="#五、通过配置方式发送请求" class="headerlink" title="五、通过配置方式发送请求"></a>五、通过配置方式发送请求</h2><blockquote>
<p><code>get</code>请求是发送参数，在<code>params</code>中定义。而<code>POST</code>请求是发送<code>request body</code>,需要在<code>data</code>中定义</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// get 在params中定义</span></span><br><span class="line">axios(&#123;</span><br><span class="line">    url:<span class="string">"pakage.json"</span>,</span><br><span class="line">    method:<span class="string">"get"</span>,</span><br><span class="line">    params:&#123;</span><br><span class="line">        userId:<span class="string">"123"</span></span><br><span class="line">    &#125;,</span><br><span class="line">    headers:&#123;</span><br><span class="line">        token:<span class="string">"http-test"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;).then(<span class="function"><span class="params">res</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res.data);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// post 在data中定义</span></span><br><span class="line">axios(&#123;</span><br><span class="line">    url:<span class="string">"pakage.json"</span>,</span><br><span class="line">    method:<span class="string">"post"</span>,</span><br><span class="line">    data:&#123;</span><br><span class="line">        userId:<span class="string">"123"</span></span><br><span class="line">    &#125;,</span><br><span class="line">    headers:&#123;</span><br><span class="line">        token:<span class="string">"http-test"</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;).then(<span class="function"><span class="params">res</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res.data);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="六、执行多个并发请求"><a href="#六、执行多个并发请求" class="headerlink" title="六、执行多个并发请求"></a>六、执行多个并发请求</h2><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getUserAcount</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 返回一个promise对象</span></span><br><span class="line">    <span class="keyword">return</span> axios.get(<span class="string">"/user/1234"</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getUserPermissions</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 返回一个promise对象</span></span><br><span class="line">    <span class="keyword">return</span> axios.get(<span class="string">"/user/1234/getUserPermissions"</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//一次性返回两个接口</span></span><br><span class="line">axios.all([getUserAccount(),getUserPerssions()]).then(axios.spread(<span class="function">(<span class="params">acct, perms</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// spread展开两个返回的结果</span></span><br><span class="line">    <span class="comment">//两个请求现已完成</span></span><br><span class="line">&#125;))</span><br></pre></td></tr></table></figure>
<h2 id="七、全局拦截"><a href="#七、全局拦截" class="headerlink" title="七、全局拦截"></a>七、全局拦截</h2><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">new</span> Vue(&#123;</span><br><span class="line">    el:<span class="string">"app"</span>,</span><br><span class="line">    data:&#123;</span><br><span class="line">        msg:<span class="string">""</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 初始化生命周期的一个函数</span></span><br><span class="line">    mounted:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">     <span class="comment">//拦截请求之前</span></span><br><span class="line">       axios.interceptors.request.use(<span class="function"><span class="params">config</span>=&gt;</span>&#123;</span><br><span class="line">           <span class="comment">//这里做一些拦截操作,拦截用户的请求 请求之前做一些loading处理</span></span><br><span class="line">           <span class="keyword">return</span> config;</span><br><span class="line">       &#125;)</span><br><span class="line">       <span class="comment">//拦截响应之后处理</span></span><br><span class="line">       axios.interceptors.response.use(<span class="function"><span class="params">response</span>=&gt;</span>&#123;</span><br><span class="line">           <span class="comment">//这里做一些拦截操作,响应以后做什么，在返回数据</span></span><br><span class="line">           <span class="keyword">return</span> response;</span><br><span class="line">       &#125;)</span><br><span class="line">    &#125;,</span><br><span class="line"></span><br><span class="line">    methods: &#123;</span><br><span class="line">        <span class="keyword">get</span>: function() &#123;</span><br><span class="line">        </span><br><span class="line">        &#125;,</span><br><span class="line">        post:<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">           </span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="八、请求封装、异常统一处理"><a href="#八、请求封装、异常统一处理" class="headerlink" title="八、请求封装、异常统一处理"></a>八、请求封装、异常统一处理</h2><blockquote>
<p>vue中采用axios处理网络请求，避免请求接口重复代码，以及各种网络情况造成的异常情况的判断，采用axios请求封装和异常拦截操作</p>
</blockquote>
<h3 id="8-1-axios-请求封装"><a href="#8-1-axios-请求封装" class="headerlink" title="8.1 axios 请求封装"></a>8.1 axios 请求封装</h3><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//  引入axios文件包</span></span><br><span class="line"><span class="keyword">import</span> axios <span class="keyword">from</span> <span class="string">'axios'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// POST 方法封装  (参数处理)</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> postRequest = <span class="function">(<span class="params">url, params</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> axios(&#123;</span><br><span class="line">    method: <span class="string">'post'</span>,</span><br><span class="line">    url: url,</span><br><span class="line">    data: params,</span><br><span class="line">    transformRequest: [<span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">let</span> ret = <span class="string">''</span></span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">let</span> it <span class="keyword">in</span> data) &#123;</span><br><span class="line">        ret += <span class="built_in">encodeURIComponent</span>(it) + <span class="string">'='</span> + <span class="built_in">encodeURIComponent</span>(data[it]) + <span class="string">'&amp;'</span></span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> ret</span><br><span class="line">    &#125;],</span><br><span class="line">    headers: &#123;</span><br><span class="line">      <span class="string">'Content-Type'</span>: <span class="string">'application/x-www-form-urlencoded'</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// POST 方法封装  (文件上传)</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> uploadFileRequest = <span class="function">(<span class="params">url, params</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> axios(&#123;</span><br><span class="line">    method: <span class="string">'post'</span>,</span><br><span class="line">    url: url,</span><br><span class="line">    data: params,</span><br><span class="line">    headers: &#123;</span><br><span class="line">      <span class="string">'Content-Type'</span>: <span class="string">'multipart/form-data'</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//  GET 方法封装</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> getRequest = <span class="function">(<span class="params">url</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> axios(&#123;</span><br><span class="line">    method: <span class="string">'get'</span>,</span><br><span class="line">    url: url</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//  PUT 方法封装</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> putRequest = <span class="function">(<span class="params">url, params</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> axios(&#123;</span><br><span class="line">    method: <span class="string">'put'</span>,</span><br><span class="line">    url: url,</span><br><span class="line">    data: params,</span><br><span class="line">    transformRequest: [<span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">let</span> ret = <span class="string">''</span></span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">let</span> it <span class="keyword">in</span> data) &#123;</span><br><span class="line">        ret += <span class="built_in">encodeURIComponent</span>(it) + <span class="string">'='</span> + <span class="built_in">encodeURIComponent</span>(data[it]) + <span class="string">'&amp;'</span></span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> ret</span><br><span class="line">    &#125;],</span><br><span class="line">    headers: &#123;</span><br><span class="line">      <span class="string">'Content-Type'</span>: <span class="string">'application/x-www-form-urlencoded'</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//  DELETE 方法封装</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> deleteRequest = <span class="function">(<span class="params">url</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> axios(&#123;</span><br><span class="line">    method: <span class="string">'delete'</span>,</span><br><span class="line">    url: url</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="8-2-axios请求异常统一处理"><a href="#8-2-axios请求异常统一处理" class="headerlink" title="8.2 axios请求异常统一处理"></a>8.2 axios请求异常统一处理</h3><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 引入依赖包</span></span><br><span class="line"><span class="keyword">import</span> axios <span class="keyword">from</span> <span class="string">'axios'</span></span><br><span class="line"><span class="keyword">import</span> &#123;Message&#125; <span class="keyword">from</span> <span class="string">'element-ui'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//  REQUEST 请求异常拦截</span></span><br><span class="line">axios.interceptors.request.use(<span class="function"><span class="params">config</span>=&gt;</span> &#123;</span><br><span class="line"> <span class="comment">//==========  所有请求之前都要执行的操作  ==============</span></span><br><span class="line">  <span class="keyword">return</span> config;</span><br><span class="line">&#125;, err=&gt; &#123;</span><br><span class="line"> <span class="comment">//==================  错误处理  ====================</span></span><br><span class="line">  Message.error(&#123;<span class="attr">message</span>: <span class="string">'请求超时!'</span>&#125;);</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Promise</span>.resolve(err);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">//  RESPONSE 响应异常拦截</span></span><br><span class="line">axios.interceptors.response.use(<span class="function"><span class="params">data</span>=&gt;</span> &#123;</span><br><span class="line"><span class="comment">//==============  所有请求完成后都要执行的操作  ==================</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 第一种方式</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 根据返回的code值来做不同的处理（和后端约定）</span></span><br><span class="line">    <span class="keyword">switch</span> (data.code) &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">'0'</span>:</span><br><span class="line">            <span class="comment">// exp: 修复iPhone 6+ 微信点击返回出现页面空白的问题</span></span><br><span class="line">            <span class="keyword">if</span> (isIOS()) &#123;</span><br><span class="line">                <span class="comment">// 异步以保证数据已渲染到页面上</span></span><br><span class="line">                setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">                    <span class="comment">// 通过滚动强制浏览器进行页面重绘</span></span><br><span class="line">                    <span class="built_in">document</span>.body.scrollTop += <span class="number">1</span></span><br><span class="line">                &#125;, <span class="number">0</span>)</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 这一步保证数据返回，如果没有return则会走接下来的代码，不是未登录就是报错</span></span><br><span class="line">            <span class="keyword">return</span> data</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 需要重新登录</span></span><br><span class="line">        <span class="keyword">case</span> <span class="string">'SHIRO_E5001'</span>:</span><br><span class="line">            <span class="comment">// 微信生产环境下授权登录</span></span><br><span class="line">            <span class="keyword">if</span> (isWeChat() &amp;&amp; IS_PRODUCTION) &#123;</span><br><span class="line">                axios.get(apis.common.wechat.authorizeUrl).then(<span class="function">(<span class="params">&#123; result &#125;</span>) =&gt;</span> &#123;</span><br><span class="line">                    location.replace(global.decodeURIComponent(result))</span><br><span class="line">                &#125;)</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// 否则跳转到h5登录并带上跳转路由</span></span><br><span class="line">                <span class="keyword">const</span> search = encodeSearchParams(&#123;</span><br><span class="line">                    next: location.href,</span><br><span class="line">                &#125;)</span><br><span class="line"></span><br><span class="line">                location.replace(<span class="string">`/user/login`</span>)</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 不显示提示消息</span></span><br><span class="line">            data.description = <span class="string">''</span></span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 若不是正确的返回code，且已经登录，就抛出错误</span></span><br><span class="line">    <span class="keyword">const</span> err = <span class="keyword">new</span> <span class="built_in">Error</span>(data.description)</span><br><span class="line"></span><br><span class="line">    err.data = data</span><br><span class="line">    err.response = response</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 第二种方式，仅对200和error状态处理</span></span><br><span class="line">  <span class="keyword">if</span> (data.status &amp;&amp; data.status == <span class="number">200</span> &amp;&amp; data.data.status == <span class="string">'error'</span>) &#123;</span><br><span class="line">    Message.error(&#123;<span class="attr">message</span>: data.data.msg&#125;);</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> data;</span><br><span class="line">&#125;, err=&gt; &#123;</span><br><span class="line"><span class="comment">//==============  错误处理  ====================</span></span><br><span class="line">   <span class="keyword">if</span> (err &amp;&amp; err.response) &#123;</span><br><span class="line">        <span class="keyword">switch</span> (err.response.status) &#123;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">400</span>: err.message = <span class="string">'请求错误(400)'</span>; <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">401</span>: err.message = <span class="string">'未授权，请重新登录(401)'</span>; <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">403</span>: err.message = <span class="string">'拒绝访问(403)'</span>; <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">404</span>: err.message = <span class="string">'请求出错(404)'</span>; <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">408</span>: err.message = <span class="string">'请求超时(408)'</span>; <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">500</span>: err.message = <span class="string">'服务器错误(500)'</span>; <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">501</span>: err.message = <span class="string">'服务未实现(501)'</span>; <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">502</span>: err.message = <span class="string">'网络错误(502)'</span>; <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">503</span>: err.message = <span class="string">'服务不可用(503)'</span>; <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">504</span>: err.message = <span class="string">'网络超时(504)'</span>; <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">505</span>: err.message = <span class="string">'HTTP版本不受支持(505)'</span>; <span class="keyword">break</span>;</span><br><span class="line">            <span class="keyword">default</span>: err.message = <span class="string">`连接出错(<span class="subst">$&#123;err.response.status&#125;</span>)!`</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        err.message = <span class="string">'连接服务器失败!'</span></span><br><span class="line">    &#125;</span><br><span class="line">  Message.err( &#123;<span class="attr">message</span>: err.message &#125; )</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Promise</span>.resolve(err);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>请求出错的时候执行的是：<code>Promise.resolve(err)</code>;，而不是<code>Promise.reject(err)</code>;，这样无论请求成功还是失败，在成功的回调中都能收到通知</p>
</blockquote>
<h3 id="8-3-vue-项目中使用该方法"><a href="#8-3-vue-项目中使用该方法" class="headerlink" title="8.3 vue 项目中使用该方法"></a>8.3 vue 项目中使用该方法</h3><blockquote>
<p>在main.js中导入所有请求方法</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//  导入所有请求方法</span></span><br><span class="line"><span class="keyword">import</span> &#123;getRequest,postRequest,deleteRequest,putRequest&#125; <span class="keyword">from</span> <span class="string">'./utils/api'</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>将请求方法添加至 <code>Vue.prototype</code> 上</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//  向VUE的原型上添加请求方法</span></span><br><span class="line">Vue.prototype.getRequest = getRequest;</span><br><span class="line">Vue.prototype.postRequest = postRequest;</span><br><span class="line">Vue.prototype.deleteRequest = deleteRequest;</span><br><span class="line">Vue.prototype.putRequest = putRequest;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>发送请求（请求方法的调用）</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//  发送网络请求</span></span><br><span class="line"><span class="keyword">this</span>.postRequest(<span class="string">'/login'</span>, &#123;userName，password&#125;).then(<span class="function"><span class="params">resp</span>=&gt;</span> &#123;</span><br><span class="line">        ...</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="九、接口封装处理"><a href="#九、接口封装处理" class="headerlink" title="九、接口封装处理"></a>九、接口封装处理</h2><blockquote>
<p><code>vue</code>中<code>Axios</code>的封装与<code>API</code>接口的管理详解</p>
</blockquote>
<h3 id="9-1-axios的封装"><a href="#9-1-axios的封装" class="headerlink" title="9.1 axios的封装"></a>9.1 axios的封装</h3><blockquote>
<p>在<code>vue</code>项目中，和后台交互获取数据这块，我们通常使用的是<code>axios</code>库，它是基于<code>promise</code>的<code>http</code>库，可运行在浏览器端和<code>node.js</code>中。他有很多优秀的特性，例如拦截请求和响应、取消请求、转换<code>json</code>、客户端防御<code>XSRF</code>等</p>
</blockquote>
<ul>
<li>一般我会在项目的<code>src</code>目录中，新建一个<code>request</code>文件夹，然后在里面新建一个<code>http.js</code>和一个<code>api.js</code>文件。<code>http.js</code>文件用来封装我们的<code>axios</code>，<code>api.js</code>用来统一管理我们的接口</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 在http.js中引入axios</span></span><br><span class="line"><span class="keyword">import</span> axios <span class="keyword">from</span> <span class="string">'axios'</span>; <span class="comment">// 引入axios</span></span><br><span class="line"><span class="keyword">import</span> QS <span class="keyword">from</span> <span class="string">'qs'</span>; <span class="comment">// 引入qs模块，用来序列化post类型的数据，后面会提到</span></span><br><span class="line"><span class="comment">// vant的toast提示框组件，大家可根据自己的ui组件更改。</span></span><br><span class="line"><span class="keyword">import</span> &#123; Toast &#125; <span class="keyword">from</span> <span class="string">'vant'</span>;</span><br></pre></td></tr></table></figure>
<h3 id="9-2-环境的切换"><a href="#9-2-环境的切换" class="headerlink" title="9.2 环境的切换"></a>9.2 环境的切换</h3><blockquote>
<p>我们的项目环境可能有开发环境、测试环境和生产环境。我们通过<code>node</code>的环境变量来匹配我们的默认的接口<code>url</code>前缀。<code>axios.defaults.baseURL</code>可以设置<code>axios</code>的默认请求地址就不多说了</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 环境的切换</span></span><br><span class="line"><span class="keyword">if</span> (process.env.NODE_ENV == <span class="string">'development'</span>) &#123; </span><br><span class="line"> axios.defaults.baseURL = <span class="string">'https://www.baidu.com'</span>;&#125; </span><br><span class="line"><span class="keyword">else</span> <span class="keyword">if</span> (process.env.NODE_ENV == <span class="string">'debug'</span>) &#123; </span><br><span class="line"> axios.defaults.baseURL = <span class="string">'https://www.ceshi.com'</span>;</span><br><span class="line">&#125; </span><br><span class="line"><span class="keyword">else</span> <span class="keyword">if</span> (process.env.NODE_ENV == <span class="string">'production'</span>) &#123; </span><br><span class="line"> axios.defaults.baseURL = <span class="string">'https://www.production.com'</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="9-3-设置请求超时"><a href="#9-3-设置请求超时" class="headerlink" title="9.3 设置请求超时"></a>9.3 设置请求超时</h3><blockquote>
<p>通过<code>axios.defaults.timeout</code>设置默认的请求超时时间。例如超过了10s，就会告知用户当前请求超时，请刷新等</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">axios.defaults.timeout = 10000;</span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>post</code>请求头的设置<code>post</code>请求的时候，我们需要加上一个请求头，所以可以在这里进行一个默认的设置，即设置<code>post</code>的请求头为<code>application/x-www-form-urlencoded;charset=UTF-8</code></p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">axios.defaults.headers.post[&apos;Content-Type&apos;] = &apos;application/x-www-form-urlencode</span><br></pre></td></tr></table></figure>
<h3 id="9-4-请求拦截"><a href="#9-4-请求拦截" class="headerlink" title="9.4 请求拦截"></a>9.4 请求拦截</h3><blockquote>
<p>我们在发送请求前可以进行一个请求的拦截，为什么要拦截呢，我们拦截请求是用来做什么的呢？比如，有些请求是需要用户登录之后才能访问的，或者post请求的时候，我们需要序列化我们提交的数据。这时候，我们可以在请求被发送之前进行一个拦截，从而进行我们想要的操作</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 先导入vuex,因为我们要使用到里面的状态对象</span></span><br><span class="line"><span class="comment">// vuex的路径根据自己的路径去写</span></span><br><span class="line"><span class="keyword">import</span> store <span class="keyword">from</span> <span class="string">'@/store/index'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 请求拦截器axios.interceptors.request.use( </span></span><br><span class="line"> config =&gt; &#123; </span><br><span class="line"> <span class="comment">// 每次发送请求之前判断vuex中是否存在token </span></span><br><span class="line"> <span class="comment">// 如果存在，则统一在http请求的header都加上token，这样后台根据token判断你的登录情况</span></span><br><span class="line"> <span class="comment">// 即使本地存在token，也有可能token是过期的，所以在响应拦截器中要对返回状态进行判断 </span></span><br><span class="line"> <span class="keyword">const</span> token = store.state.token; </span><br><span class="line"> token &amp;&amp; (config.headers.Authorization = token); </span><br><span class="line"> <span class="keyword">return</span> config; </span><br><span class="line"> &#125;, </span><br><span class="line"> error =&gt; &#123; </span><br><span class="line"> <span class="keyword">return</span> <span class="built_in">Promise</span>.error(error); </span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<blockquote>
<p>一般是在登录完成之后，将用户的<code>token</code>通过<code>localStorage</code>或者<code>cookie</code>存在本地，然后用户每次在进入页面的时候（即在<code>main.js</code>中），会首先从本地存储中读取<code>token</code>，如果<code>token</code>存在说明用户已经登陆过，则更新vuex中的token状态。然后，在每次请求接口的时候，都会在请求的<code>header</code>中携带<code>token</code>，后台人员就可以根据你携带的<code>token</code>来判断你的登录是否过期，如果没有携带，则说明没有登录过。这时候或许有些小伙伴会有疑问了，就是每个请求都携带<code>token</code>，那么要是一个页面不需要用户登录就可以访问的怎么办呢？其实，你前端的请求可以携带<code>token</code>，但是后台可以选择不接收啊！</p>
</blockquote>
<h3 id="9-5-响应的拦截"><a href="#9-5-响应的拦截" class="headerlink" title="9.5 响应的拦截"></a>9.5 响应的拦截</h3><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 响应拦截器</span></span><br><span class="line">axios.interceptors.response.use( </span><br><span class="line"> response =&gt; &#123; </span><br><span class="line"> <span class="comment">// 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据 </span></span><br><span class="line"> <span class="comment">// 否则的话抛出错误</span></span><br><span class="line"> <span class="keyword">if</span> (response.status === <span class="number">200</span>) &#123;  </span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Promise</span>.resolve(response); </span><br><span class="line"> &#125; <span class="keyword">else</span> &#123;  </span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Promise</span>.reject(response); </span><br><span class="line"> &#125; </span><br><span class="line"> &#125;, </span><br><span class="line"> <span class="comment">// 服务器状态码不是2开头的的情况</span></span><br><span class="line"> <span class="comment">// 这里可以跟你们的后台开发人员协商好统一的错误状态码 </span></span><br><span class="line"> <span class="comment">// 然后根据返回的状态码进行一些操作，例如登录过期提示，错误提示等等</span></span><br><span class="line"> <span class="comment">// 下面列举几个常见的操作，其他需求可自行扩展</span></span><br><span class="line"> error =&gt; &#123;  </span><br><span class="line"> <span class="keyword">if</span> (error.response.status) &#123;  </span><br><span class="line">  <span class="keyword">switch</span> (error.response.status) &#123;  </span><br><span class="line">  <span class="comment">// 401: 未登录</span></span><br><span class="line">  <span class="comment">// 未登录则跳转登录页面，并携带当前页面的路径</span></span><br><span class="line">  <span class="comment">// 在登录成功后返回当前页面，这一步需要在登录页操作。  </span></span><br><span class="line">  <span class="keyword">case</span> <span class="number">401</span>:   </span><br><span class="line">   router.replace(&#123;   </span><br><span class="line">   path: <span class="string">'/login'</span>,   </span><br><span class="line">   query: &#123; </span><br><span class="line">    redirect: router.currentRoute.fullPath </span><br><span class="line">   &#125;</span><br><span class="line">   &#125;);</span><br><span class="line">   <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 403 token过期</span></span><br><span class="line">  <span class="comment">// 登录过期对用户进行提示</span></span><br><span class="line">  <span class="comment">// 清除本地token和清空vuex中token对象</span></span><br><span class="line">  <span class="comment">// 跳转登录页面  </span></span><br><span class="line">  <span class="keyword">case</span> <span class="number">403</span>:</span><br><span class="line">   Toast(&#123;</span><br><span class="line">   message: <span class="string">'登录过期，请重新登录'</span>,</span><br><span class="line">   duration: <span class="number">1000</span>,</span><br><span class="line">   forbidClick: <span class="literal">true</span></span><br><span class="line">   &#125;);</span><br><span class="line">   <span class="comment">// 清除token</span></span><br><span class="line">   localStorage.removeItem(<span class="string">'token'</span>);</span><br><span class="line">   store.commit(<span class="string">'loginSuccess'</span>, <span class="literal">null</span>);</span><br><span class="line">   <span class="comment">// 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面 </span></span><br><span class="line">   setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;   </span><br><span class="line">   router.replace(&#123;    </span><br><span class="line">    path: <span class="string">'/login'</span>,    </span><br><span class="line">    query: &#123; </span><br><span class="line">    redirect: router.currentRoute.fullPath </span><br><span class="line">    &#125;   </span><br><span class="line">   &#125;);   </span><br><span class="line">   &#125;, <span class="number">1000</span>);   </span><br><span class="line">   <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 404请求不存在</span></span><br><span class="line">  <span class="keyword">case</span> <span class="number">404</span>:</span><br><span class="line">   Toast(&#123;</span><br><span class="line">   message: <span class="string">'网络请求不存在'</span>,</span><br><span class="line">   duration: <span class="number">1500</span>,</span><br><span class="line">   forbidClick: <span class="literal">true</span></span><br><span class="line">   &#125;);</span><br><span class="line">   <span class="keyword">break</span>;</span><br><span class="line">  <span class="comment">// 其他错误，直接抛出错误提示</span></span><br><span class="line">  <span class="keyword">default</span>:</span><br><span class="line">   Toast(&#123;</span><br><span class="line">   message: error.response.data.message,</span><br><span class="line">   duration: <span class="number">1500</span>,</span><br><span class="line">   forbidClick: <span class="literal">true</span></span><br><span class="line">   &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Promise</span>.reject(error.response);</span><br><span class="line"> &#125;</span><br><span class="line"> &#125; </span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>响应拦截器很好理解，就是服务器返回给我们的数据，我们在拿到之前可以对他进行一些处理。例如上面的思想：如果后台返回的状态码是200，则正常返回数据，否则的根据错误的状态码类型进行一些我们需要的错误，其实这里主要就是进行了错误的统一处理和没登录或登录过期后调整登录页的一个操作</p>
</blockquote>
<ul>
<li>要注意的是，上面的<code>Toast()</code>方法，是我引入的<code>vant</code>库中的<code>toast</code>轻提示组件，你根据你的<code>ui</code>库，对应使用你的一个提示组件</li>
</ul>
<h3 id="9-6-封装get方法和post方法"><a href="#9-6-封装get方法和post方法" class="headerlink" title="9.6 封装get方法和post方法"></a>9.6 封装get方法和post方法</h3><blockquote>
<p>我们常用的<code>ajax</code>请求方法有<code>get</code>、<code>post</code>、<code>put</code>等方法。<code>axios</code>对应的也有很多类似的方法，不清楚的可以看下文档。但是为了简化我们的代码，我们还是要对其进行一个简单的封装。下面我们主要封装两个方法：<code>get</code>和<code>post</code></p>
</blockquote>
<ul>
<li><code>get</code>方法：我们通过定义一个<code>get</code>函数，<code>get</code>函数有两个参数，第一个参数表示我们要请求的<code>url</code>地址，第二个参数是我们要携带的请求参数。<code>get</code>函数返回一个<code>promise</code>对象，当<code>axios</code>其请求成功时<code>resolve</code>服务器返回值，请求失败时<code>reject</code>错误值。最后通过<code>export</code>抛出<code>get</code>函数</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * get方法，对应get请求</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;String&#125;</span> </span>url [请求的url地址]</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Object&#125;</span> </span>params [请求时携带的参数]</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">get</span>(<span class="params">url, params</span>)</span>&#123; </span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span>&#123; </span><br><span class="line"> axios.get(url, &#123;  </span><br><span class="line">  params: params </span><br><span class="line"> &#125;).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">  resolve(res.data);</span><br><span class="line"> &#125;).catch(<span class="function"><span class="params">err</span> =&gt;</span>&#123;</span><br><span class="line">  reject(err.data) </span><br><span class="line"> &#125;) </span><br><span class="line">&#125;);&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>post</code>方法：原理同<code>get</code>基本一样，但是要注意的是，<code>post</code>方法必须要使用对提交从参数对象进行序列化的操作，所以这里我们通过<code>node</code>的<code>qs</code>模块来序列化我们的参数。这个很重要，如果没有序列化操作，后台是拿不到你提交的数据的</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">/** </span></span><br><span class="line"><span class="comment"> * post方法，对应post请求 </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;String&#125;</span> </span>url [请求的url地址] </span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Object&#125;</span> </span>params [请求时携带的参数] </span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">post</span>(<span class="params">url, params</span>) </span>&#123;</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  axios.post(url, QS.stringify(params))</span><br><span class="line"> .then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">  resolve(res.data);</span><br><span class="line"> &#125;)</span><br><span class="line"> .catch(<span class="function"><span class="params">err</span> =&gt;</span>&#123;</span><br><span class="line">  reject(err.data)</span><br><span class="line"> &#125;)</span><br><span class="line"> &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>axios.get()</code>方法和<code>axios.post()</code>在提交数据时参数的书写方式还是有区别的。区别就是，<code>get</code>的第二个参数是一个<code>{}</code>，然后这个对象的<code>params</code>属性值是一个参数对象的。而<code>post</code>的第二个参数就是一个参数对象</p>
</blockquote>
<h3 id="9-7-api的统一管理"><a href="#9-7-api的统一管理" class="headerlink" title="9.7 api的统一管理"></a>9.7 api的统一管理</h3><blockquote>
<p>首先我们在<code>api.js</code>中引入我们封装的<code>get</code>和<code>post</code>方法</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">/** </span></span><br><span class="line"><span class="comment"> * api接口统一管理</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">import</span> &#123; <span class="keyword">get</span>, post &#125; from './http'</span><br></pre></td></tr></table></figure>
<p>在<code>api.js</code>中</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">export const apiAddress = param =&gt; post(&apos;api/v1/users&apos;,param)</span><br></pre></td></tr></table></figure>
<p>在我们的页面中可以这样调用我们的<code>api</code>接口</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; apiAddress &#125; <span class="keyword">from</span> <span class="string">'@/request/api'</span>;<span class="comment">// 导入我们的api接口</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;  </span><br><span class="line"> name: <span class="string">'Address'</span>, </span><br><span class="line"> created () &#123;</span><br><span class="line">  <span class="keyword">this</span>.onLoad();</span><br><span class="line"> &#125;,</span><br><span class="line"> methods: &#123;   </span><br><span class="line">  <span class="comment">// 获取数据   </span></span><br><span class="line">  onLoad() &#123;</span><br><span class="line">   <span class="comment">// 调用api接口，并且提供了两个参数    </span></span><br><span class="line">   apiAddress(&#123;     </span><br><span class="line">    type: <span class="number">0</span>,     </span><br><span class="line">    sort: <span class="number">1</span>    </span><br><span class="line">   &#125;).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 获取数据成功后的其他操作</span></span><br><span class="line">    ………………    </span><br><span class="line">   &#125;)   </span><br><span class="line">  &#125;  </span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="9-8-完整封装代码"><a href="#9-8-完整封装代码" class="headerlink" title="9.8 完整封装代码"></a>9.8 完整封装代码</h3><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**axios封装</span></span><br><span class="line"><span class="comment"> * 请求拦截、相应拦截、错误统一处理</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">import</span> axios <span class="keyword">from</span> <span class="string">'axios'</span>;</span><br><span class="line"><span class="keyword">import</span> QS <span class="keyword">from</span> <span class="string">'qs'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;</span><br><span class="line">	Toast</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">from</span> <span class="string">'vant'</span>;</span><br><span class="line"><span class="keyword">import</span> store <span class="keyword">from</span> <span class="string">'../store/index'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 环境的切换</span></span><br><span class="line"><span class="keyword">if</span> (process.env.NODE_ENV == <span class="string">'development'</span>) &#123;</span><br><span class="line">	axios.defaults.baseURL = <span class="string">'/api'</span>;</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (process.env.NODE_ENV == <span class="string">'debug'</span>) &#123;</span><br><span class="line">	axios.defaults.baseURL = <span class="string">''</span>;</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (process.env.NODE_ENV == <span class="string">'production'</span>) &#123;</span><br><span class="line">	axios.defaults.baseURL = <span class="string">'http://api.123dailu.com/'</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 请求超时时间</span></span><br><span class="line">axios.defaults.timeout = <span class="number">10000</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// post请求头</span></span><br><span class="line">axios.defaults.headers.post[<span class="string">'Content-Type'</span>] = <span class="string">'application/x-www-form-urlencoded;charset=UTF-8'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 请求拦截器</span></span><br><span class="line">axios.interceptors.request.use(</span><br><span class="line">config = &gt; &#123;</span><br><span class="line">	<span class="comment">// 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了</span></span><br><span class="line">	<span class="comment">// 即使本地存在token，也有可能token是过期的，所以在响应拦截器中要对返回状态进行判断</span></span><br><span class="line">	<span class="keyword">const</span> token = store.state.token;</span><br><span class="line">	token &amp;&amp; (config.headers.Authorization = token);</span><br><span class="line">	<span class="keyword">return</span> config;</span><br><span class="line">&#125;, error = &gt; &#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">Promise</span>.error(error);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 响应拦截器</span></span><br><span class="line">axios.interceptors.response.use(</span><br><span class="line">response = &gt; &#123;</span><br><span class="line">	<span class="keyword">if</span> (response.status === <span class="number">200</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">Promise</span>.resolve(response);</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">Promise</span>.reject(response);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;,</span><br><span class="line"><span class="comment">// 服务器状态码不是200的情况 </span></span><br><span class="line">error = &gt; &#123;</span><br><span class="line">	<span class="keyword">if</span> (error.response.status) &#123;</span><br><span class="line">		<span class="keyword">switch</span> (error.response.status) &#123;</span><br><span class="line">			<span class="comment">// 401: 未登录    </span></span><br><span class="line">			<span class="comment">// 未登录则跳转登录页面，并携带当前页面的路径    </span></span><br><span class="line">			<span class="comment">// 在登录成功后返回当前页面，这一步需要在登录页操作。    </span></span><br><span class="line">		<span class="keyword">case</span> <span class="number">401</span>:</span><br><span class="line">			router.replace(&#123;</span><br><span class="line">				path: <span class="string">'/login'</span>,</span><br><span class="line">				query: &#123;</span><br><span class="line">					redirect: router.currentRoute.fullPath</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;);</span><br><span class="line">			<span class="keyword">break</span>;</span><br><span class="line">			<span class="comment">// 403 token过期    </span></span><br><span class="line">			<span class="comment">// 登录过期对用户进行提示    </span></span><br><span class="line">			<span class="comment">// 清除本地token和清空vuex中token对象    </span></span><br><span class="line">			<span class="comment">// 跳转登录页面    </span></span><br><span class="line">		<span class="keyword">case</span> <span class="number">403</span>:</span><br><span class="line">			Toast(&#123;</span><br><span class="line">				message: <span class="string">'登录过期，请重新登录'</span>,</span><br><span class="line">				duration: <span class="number">1000</span>,</span><br><span class="line">				forbidClick: <span class="literal">true</span></span><br><span class="line">			&#125;);</span><br><span class="line">			<span class="comment">// 清除token     </span></span><br><span class="line">			localStorage.removeItem(<span class="string">'token'</span>);</span><br><span class="line">			store.commit(<span class="string">'loginSuccess'</span>, <span class="literal">null</span>);</span><br><span class="line">			<span class="comment">// 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面</span></span><br><span class="line">			setTimeout(() = &gt; &#123;</span><br><span class="line">				router.replace(&#123;</span><br><span class="line">					path: <span class="string">'/login'</span>,</span><br><span class="line">					query: &#123;</span><br><span class="line">						redirect: router.currentRoute.fullPath</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;);</span><br><span class="line">			&#125;, <span class="number">1000</span>);</span><br><span class="line">			<span class="keyword">break</span>;</span><br><span class="line">			<span class="comment">// 404请求不存在    </span></span><br><span class="line">		<span class="keyword">case</span> <span class="number">404</span>:</span><br><span class="line">			Toast(&#123;</span><br><span class="line">				message: <span class="string">'网络请求不存在'</span>,</span><br><span class="line">				duration: <span class="number">1500</span>,</span><br><span class="line">				forbidClick: <span class="literal">true</span></span><br><span class="line">			&#125;);</span><br><span class="line">			<span class="keyword">break</span>;</span><br><span class="line">			<span class="comment">// 其他错误，直接抛出错误提示    </span></span><br><span class="line">		<span class="keyword">default</span>:</span><br><span class="line">			Toast(&#123;</span><br><span class="line">				message: error.response.data.message,</span><br><span class="line">				duration: <span class="number">1500</span>,</span><br><span class="line">				forbidClick: <span class="literal">true</span></span><br><span class="line">			&#125;);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">Promise</span>.reject(error.response);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">/** </span></span><br><span class="line"><span class="comment"> * get方法，对应get请求</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;String&#125;</span> </span>url [请求的url地址]</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Object&#125;</span> </span>params [请求时携带的参数]</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">get</span>(<span class="params">url, params</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>((resolve, reject) = &gt; &#123;</span><br><span class="line">		axios.get(url, &#123;</span><br><span class="line">			params: params</span><br><span class="line">		&#125;).then(res = &gt; &#123;</span><br><span class="line">			resolve(res.data);</span><br><span class="line">		&#125;).</span><br><span class="line">		<span class="keyword">catch</span> (err = &gt; &#123;</span><br><span class="line">			reject(err.data)</span><br><span class="line">		&#125;)</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/** </span></span><br><span class="line"><span class="comment"> * post方法，对应post请求</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;String&#125;</span> </span>url [请求的url地址]</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Object&#125;</span> </span>params [请求时携带的参数]</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">post</span>(<span class="params">url, params</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>((resolve, reject) = &gt; &#123;</span><br><span class="line">		axios.post(url, QS.stringify(params)).then(res = &gt; &#123;</span><br><span class="line">			resolve(res.data);</span><br><span class="line">		&#125;).</span><br><span class="line">		<span class="keyword">catch</span> (err = &gt; &#123;</span><br><span class="line">			reject(err.data)</span><br><span class="line">		&#125;)</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2018/08/28/vue-router/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2018/08/28/vue-$vm-method-props/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
